package com.mhdanh.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ViewImgController {
	
	@RequestMapping("/viewimg/{name:.+}")
	public void viewimg(@PathVariable("name") String name,HttpServletResponse response) throws IOException{
		String pathImg = "D:/mhdanh/"+name;
		viewImg(response, pathImg, name);
	}
	
	@RequestMapping("/viewimg/index")
	public String index(){
		return "viewimg/index";
	}
	
	public void viewImg(HttpServletResponse response,String outputPath,String filename) throws IOException{
		File file = new File(outputPath);
		if(file.exists()){
			FileInputStream inputStream= new FileInputStream(file);
			ServletOutputStream outStream = response.getOutputStream();
	        byte[] buffer = new byte[4096];
	        int bytesRead = -1;
	        response.setContentType("image/*");
			response.setHeader("Content-Disposition","inline;filename="+filename);
			response.setContentLength((int) file.length());
	        while ((bytesRead = inputStream.read(buffer)) != -1) {
	            outStream.write(buffer, 0, bytesRead);
	        }
	        inputStream.close();
	        outStream.close();
		}
	}
}
